from pprint import pprint

from django.contrib.auth.models import Group, Permission
from rest_framework import serializers
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.meiduo_admin.utils import CurPagination
from apps.users.models import User


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {'password': {'write_only': True, 'required': False}}

    def create(self, validated_data):
        user = super().create(validated_data)
        password = validated_data['password']
        if not password:
            raise serializers.ValidationError('密码错误')
        user.set_password(password)
        user.is_staff = True
        user.save()
        return user

    def update(self, instance, validated_data):
        password = validated_data.get('password')
        user = super().update(instance, validated_data)
        if password:
            user.set_password(password)
            user.save()
        return user


class AdminsView(ModelViewSet):
    permission_classes = [IsAdminUser]
    pagination_class = CurPagination
    lookup_value_regex = '\d+'
    queryset = User.objects.filter(is_staff=True, is_active=True).order_by('id')
    serializer_class = AdminSerializer

    def simple(self, request):
        """用户组池"""
        data = Group.objects.order_by('id').values('id', 'name')
        return Response(data)
